﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using System.Reflection;
/**
 * Utility class for getting the name of a member property of an object
 * From : 
 * http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/f44dc57a9dc5168d/02c312dcf8a9a769#4805324df6b30218
 * 
 */
namespace Universum.Infrastructure.Utils
{
	public static class MemberUtil<TType>
	{
		public static string MemberName<TResult>(Expression<Func<TType, TResult>> member)
		{
			return MemberUtil.MemberName<TType, TResult>(member);
		}
	}

	static class MemberUtil//<TType>
	{
		public static string MemberName<TType,
	TResult>(Expression<Func<TType, TResult>> member)
		{
			return MemberInfo(member).Name;
		}
		public static MemberInfo MemberInfo<TType,
	TResult>(Expression<Func<TType, TResult>> member)
		{
			return ParseMemberInfo(member);
		}
		public static string MemberName<TType>(Expression<Action<TType>>
	member)
		{
			return MemberInfo(member).Name;
		}
		public static MemberInfo
	MemberInfo<TType>(Expression<Action<TType>> member)
		{
			return ParseMemberInfo(member);
		}
		static MemberInfo ParseMemberInfo(Expression expression)
		{
			while (expression.NodeType == ExpressionType.Lambda)
			{
				expression = ((LambdaExpression)expression).Body;
			}
			switch (expression.NodeType)
			{
				case ExpressionType.MemberAccess:
					return ((MemberExpression)expression).Member;
				case ExpressionType.Call:
					return ((MethodCallExpression)expression).Method;
				default:
					throw new NotSupportedException("Unable to parse " +
	expression.NodeType.ToString());
			}
		}
	}
}
